package com.ivan.toolkit.common;

import java.util.regex.Pattern;

public class Inputs {
	
	public static StringVerifier at(String value, String name) {
		return new StringVerifier(value, name);
	}
		
	public static class StringVerifier {
		
		String value;
		
		String name;

		public StringVerifier(String value, String name) {
			super();
			this.value = value;
			this.name = name;
		}

		
		public StringVerifier _notNull() {
			if(value == null)
				throw new RuntimeException(name + "不能为空");
			return this;
		}
		
		public StringVerifier _notEmpty() {
			if(value == null || value.isEmpty())
				throw new RuntimeException(name + "不能为空");
			return this;
		}
		
		public StringVerifier _max(int max) {
			if(value.length() > max)
				throw new RuntimeException(name + "不能超过" + max + "个字符");
			return this;
		}
		
		public StringVerifier _min(int min) {
			if(value.length() < min)
				throw new RuntimeException(name + "不能少于" + min + "个字符");
			return this;
		}
		
		public StringVerifier _range(int min, int max) {
			if(value.length() < min)
				throw new RuntimeException(name + "不能少于" + min + "个字符或者超过" + max + "个字符");
			return this;
		}
		
		public StringVerifier _ip() {
			
			return this._pattern("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]"
                    + "|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$", "不是合法的IP地址");
		}
		
		public StringVerifier _username() {
			
			// 数字、26个英文字母或者下划线组成
	        return this._pattern("^\\w+$", "只能是数字、字符或下划线");
		}
		
		public StringVerifier _pattern(String patternString, String description) {

	        Pattern pattern = Pattern.compile(patternString);
			if(!pattern.matcher(value).matches())
				throw new RuntimeException(name + description);
			return this;

		}
		
		
		
	}
	
}
